package com.pacs.control;

import java.util.UUID;

import com.pacs.control.beans.ResultBean;
import com.pacs.service.beans.WxJSInfoBean;
import com.pacs.tools.LogUtil;
import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.JsTicket;
import com.jfinal.weixin.sdk.api.JsTicketApi;
import com.jfinal.weixin.sdk.api.JsTicketApi.JsApiType;

public class WeixinJSControl extends Controller{
	/**
	 * 如果要支持多公众账号，只需要在此返回各个公众号对应的 ApiConfig 对象即可 可以通过在请求 url 中挂参数来动态从数据库中获取
	 * ApiConfig 属性值
	 */
	public ApiConfig getApiConfig() {
		ApiConfig ac = new ApiConfig();

		// 配置微信 API 相关常量
		ac.setToken(PropKit.get("token"));
		ac.setAppId(PropKit.get("appId"));
		ac.setAppSecret(PropKit.get("appSecret"));

		/**
		 * 是否对消息进行加密，对应于微信平台的消息加解密方式： 1：true进行加密且必须配置 encodingAesKey
		 * 2：false采用明文模式，同时也支持混合模式
		 */
		ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(PropKit.get("encodingAesKey",
				"setting it in config file"));
		return ac;
	}
	
	
	public void index(){
		String origin = this.getRequest().getHeader("Origin");
		this.getResponse().setHeader("Access-Control-Allow-Origin", origin);
		this.getResponse().setHeader("Access-Control-Allow-Credentials", Boolean.TRUE.toString());
		
		ApiConfig apiConfig  = getApiConfig();
		ApiConfigKit.setThreadLocalApiConfig(apiConfig);
		JsTicket jsApiTicket = JsTicketApi.getTicket(JsApiType.jsapi);
		String jsapi_ticket  = jsApiTicket.getTicket();
		String nonce_str 	 = create_nonce_str();
		String url 		     = this.getRequest().getHeader("Referer");
		String timestamp 	 = create_timestamp();
		String str 			 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;
		String signature 	 = HashKit.sha1(str);
		
		Integer startTime = (int)(System.currentTimeMillis()/1000);
		Integer endTime = (int)(System.currentTimeMillis()/1000);
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("WeixinJSControl_wxjs").append("  ").append(endTime-startTime).append("  ").append(str);
		LogUtil.sysDebug(stringBuilder.toString());
		
		WxJSInfoBean infoBean = new WxJSInfoBean();
		infoBean.setAppId(apiConfig.getAppId());
		infoBean.setNonceStr(nonce_str);
		infoBean.setSignature(signature);
		infoBean.setTimestamp(timestamp);
		this.renderJson(new ResultBean(infoBean));
	}
	
	private static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}

	private static String create_nonce_str() {
		return UUID.randomUUID().toString();
	}
}
